﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Repositories.Interfaces;
using Repositories;
using System.Data;
using System.Globalization;

namespace AsiaSnackExpress
{
    public partial class EditCategory : System.Web.UI.Page
    {
        #region Properties

        IMealRepository _mealRep;
        public IMealRepository MealRep
        {
            get
            {
                if (_mealRep == null)
                {
                    _mealRep = DIHelper.Resolve<IMealRepository>();
                }
                return _mealRep;
            }

        }


        ICategoryRepository _categoryRep;
        public ICategoryRepository CategoryRep
        {
            get
            {
                if (_categoryRep == null)
                {
                    _categoryRep = DIHelper.Resolve<ICategoryRepository>();
                }
                return _categoryRep;
            }

        }

        public int CatergoryId
        {
            get
            {
                string catergoryId = Request.QueryString["id"];
                if (string.IsNullOrEmpty(catergoryId))
                    return 0;
                return int.Parse(catergoryId);
            }
        }

        Category current = null;
        public Category CurrentCategory
        {
            get
            {
                if (current == null)
                    current = new Category();
                current.EnglishName = txtNameEnglish.Text.Trim();
                current.Name = txtName.Text.Trim();
                current.Description = txtDescription.Text.Trim();
                current.EnglishDescription = txtDescrioptionEnglish.Text.Trim();
                return current;
            }
            set
            {
                if (value != null)
                {
                    txtNameEnglish.Text = value.EnglishName;
                    txtName.Text = value.Name;
                    txtDescription.Text = value.Description;
                    txtDescrioptionEnglish.Text = value.EnglishDescription;
                }
            }
        }

        public List<Meal> MealDataSource
        {
            get
            {
                return (List<Meal>)gridMeals.DataSource;
            }
            set
            {
                if (value != null && value.Count > 0)
                {
                    gridMeals.DataSource = value;
                    gridMeals.DataBind();
                }
            }
        }
        #endregion

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            DIHelper.Configure();
            base.OnLoad(e);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            //Check loock in
            CategoryRep.Refresh();
            MealRep.Refresh();
            if (!IsPostBack)
            {
                CurrentCategory = CategoryRep.FindById(CatergoryId);
                MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Admin.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var catergory = CategoryRep.FindById(CatergoryId);
                if (catergory != null)
                {
                    catergory.Name = CurrentCategory.Name;
                    catergory.EnglishName = CurrentCategory.EnglishName;
                    catergory.Description = CurrentCategory.Description;
                    catergory.EnglishDescription = CurrentCategory.EnglishDescription;
                    CategoryRep.Update(catergory);
                    lblMessage.Text = "Category Saved!";
                    CategoryRep.ApplyTheChanges();
                }
                else
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "The categeory is not found.";
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

        }

        protected void gridMeals_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.Equals("Insert"))
                {
                    Meal temp = new Meal();
                    GridViewRow row = (GridViewRow)gridMeals.FooterRow;
                    GetMealDataFromControls(row, temp);
                    var catergory = CategoryRep.FindById(CatergoryId);
                    temp.Category = catergory;
                    MealRep.Insert(temp);
                    MealRep.ApplyTheChanges();
                    gridMeals.EditIndex = -1;
                    gridMeals.ShowFooter = false;
                    MealRep.Refresh();
                    Response.Redirect(Page.Request.Url.ToString());
                }
                else if (e.CommandName.Equals("Cancel"))
                {
                    gridMeals.ShowFooter = false;
                }
                else if (e.CommandName.Equals("Delete"))
                {
                    gridMeals.EditIndex = -1;
                    gridMeals.ShowFooter = false;
                }

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        protected void gridMeals_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridMeals.EditIndex = e.NewEditIndex;
            MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);
        }
        protected void gridMeals_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridMeals.EditIndex = -1;
            MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);
        }
        protected void gridMeals_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                int currentId = int.Parse(gridMeals.DataKeys[e.RowIndex].Values[0].ToString());
                GridViewRow row = (GridViewRow)gridMeals.Rows[e.RowIndex];
                Meal temp = MealRep.FindById(currentId);
                GetMealDataFromControls(row, temp);
                gridMeals.EditIndex = -1;
                gridMeals.ShowFooter = false;
                MealRep.Refresh();
                MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);
            }
            catch (Exception ex)
            {
                //TODO: log Exception ex message
                lblMessage.Text = ex.Message;
            }
        }

        private void GetMealDataFromControls(GridViewRow row, Meal temp)
        {

            TextBox txtIndexNumber = (TextBox)row.FindControl("txtIndexNumber");
            TextBox txtName = (TextBox)row.FindControl("txtName");
            TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
            TextBox txtPriceBig = (TextBox)row.FindControl("txtPriceBig");

            TextBox txtEnglishName = (TextBox)row.FindControl("txtEnglishName");
            TextBox txtDescription = (TextBox)row.FindControl("txtDescription");
            TextBox txtEnglishDescription = (TextBox)row.FindControl("txtEnglishDescription");
            TextBox txtEnglishHighLight = (TextBox)row.FindControl("txtEnglishHighLight");
            TextBox txtHighLight = (TextBox)row.FindControl("txtHighLight");
            TextBox txtVolume = (TextBox)row.FindControl("txtVolume");


            if (temp != null)
            {
                temp.IndexNumber = txtIndexNumber.Text.Trim();
                temp.Name = txtName.Text.Trim();
                if (!string.IsNullOrEmpty(txtUnitPrice.Text.Trim()))
                    temp.Price = float.Parse(txtUnitPrice.Text.Trim());
                else
                    temp.Price = null;
                temp.EnglishName = txtEnglishName.Text.Trim();
                temp.Description = txtDescription.Text.Trim();
                temp.EnglishDescription = txtDescrioptionEnglish.Text.Trim();
                temp.EnglishHighLight = txtEnglishHighLight.Text.Trim();
                temp.HighLight = txtHighLight.Text.Trim();
                if (!string.IsNullOrEmpty(txtPriceBig.Text.Trim()))
                    temp.Price1 = float.Parse(txtPriceBig.Text.Trim());
                else
                    temp.Price1 = null;
                temp.Volume = txtVolume.Text.Trim();
                MealRep.Update(temp);
                lblMessage.Text = "Meal Saved!";
                MealRep.ApplyTheChanges();
            }
        }

        protected void gridMeals_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int currentListId = int.Parse(gridMeals.DataKeys[e.RowIndex].Values[0].ToString());
                var catergory = CategoryRep.FindById(CatergoryId);
                var meal = MealRep.FindById(currentListId);
                MealRep.Deattach(catergory);
                MealRep.DeleteMeal(meal);
                MealRep.ApplyTheChanges();
                MealRep.Refresh();
                gridMeals.ShowFooter = false;
                lblMessage.Text = "Delete Meal.";

                MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        protected void btnAddMore_Click(object sender, EventArgs e)
        {
            try
            {
                gridMeals.ShowFooter = true;

                MealDataSource = MealRep.GetAllMealByCategory(CatergoryId);


                if (gridMeals.DataSource == null)
                {
                    List<Meal> temp = new List<Meal>();
                    temp.Add(new Meal());
                    MealDataSource = temp;
                }

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        protected void gridMeals_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {

                switch (e.Row.RowState)
                {
                    case DataControlRowState.Edit:

                    case DataControlRowState.Normal:

                        break;
                    default:

                        break;
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        #endregion


    }
}